package blog.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageInfo;

import blog.entity.Article;
import blog.entity.Category;
import blog.entity.Tag;
import blog.entity.User;
import blog.service.ArticleService;
import blog.service.CategoryService;
import blog.service.TagService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
/**
 * 文章控制层
 * @author 江佳洋
 *
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private TagService tagService;
	/**
	 * 去全部文章主界面
	 * @param map
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	
	@RequestMapping("")
	public String articleList(ModelMap map,@RequestParam(required=false,defaultValue="1")Integer pageIndex,
			@RequestParam(required=false,defaultValue="10")Integer pageSize,String articleTitle,String articleStatus,
			String articleUpdateTime,String articleChildCategoryId,String articleParentCategoryId) {
		PageInfo<Article> articleList = articleService.getPageArticleList(pageIndex, pageSize,articleStatus,articleTitle,articleUpdateTime,articleChildCategoryId,articleParentCategoryId);
		List<Category> findAllCategory = categoryService.findAllCategory();
		map.put("cateList", findAllCategory);
		map.put("pageUrlPrefix", "article?pageIndex");
		map.put("pageInfo", articleList);
		map.put("articleTitle", articleTitle);
		map.put("articleUpdateTime", articleUpdateTime);
		map.put("articleStatus", articleStatus);
		if(!StrUtil.isEmptyOrUndefined(articleChildCategoryId)) {
			Category selectCategoryById = categoryService.selectCategoryById(Integer.parseInt(articleChildCategoryId));
			map.put("articleChildCategoryId", selectCategoryById);
		}
		map.put("articleParentCategoryId", articleParentCategoryId);
		return "article/article_list";
	}
	
	/**
	 * 添加文章
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String goWriteArticle(ModelMap map) {
		List<Category> findAllCategory = categoryService.findAllCategory();
		List<Tag> allTag = tagService.getAllTag();
		map.put("categoryList", findAllCategory);
		map.put("tagList", allTag);
		return "article/article_add";
	}
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String addArticle(ModelMap map,HttpServletRequest request) {
		Article article = new Article();
		//添加文章标题
		article.setArticleTitle(request.getParameter("articleTitle"));
		//添加文章内容
		article.setArticleContent(request.getParameter("articleContent"));
		//添加添加文章的人id
		User user = (User)request.getSession().getAttribute("user");
		article.setArticleUserId(user.getUserId());
		//添加文章摘要
		String articleContent = HtmlUtil.cleanHtmlTag(request.getParameter("articleContent"));
		article.setArticleSummary((articleContent.length()>150?articleContent.substring(0,150):articleContent));
		//添加修改和创建时间
		article.setArticleCreateTime(new Date());
		article.setArticleUpdateTime(new Date());
		//默认的排序
		article.setArticleOrder(1);
		//文章状态(草稿,或发布)
		article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus" )));
		//一级分类ID
		int parentCateId =Integer.parseInt(request.getParameter("articleParentCategoryId"));
		//二级分类ID
		int childCateId=Integer.parseInt(request.getParameter("articleChildCategoryId"));
		//标签
		//添加分类
		List<Category> cateList = new ArrayList<>(2);
		cateList.add(new Category(parentCateId));
		cateList.add(new Category(childCateId));
		article.setCategoryList(cateList);
		String [] tagIds =request.getParameterValues("articleTagIds");
		//添加标签
		if(tagIds!=null) {
			List<Tag> tagList = new ArrayList<>();
			for(String tag:tagIds) {
				tagList.add(new Tag(Integer.parseInt(tag)));
			}
			article.setTagList(tagList);
		}
		articleService.addArticle(article);
		return "forward:/article";
	}
	/**
	 * 根据文章id删除文章 
	 * @param articleId
	 * @return
	 */
	@RequestMapping("delete/{articleId}")
	public String deltetArticle(@PathVariable("articleId")  Integer articleId) {
		articleService.deleteArticleById(articleId);
		return "forward:/article";
	}
	/**
	 * 去修改文章信息界面
	 * @param id 文章id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String goEdit(@PathVariable("id")Integer id,ModelMap map) {
		Article articleById = articleService.getArticleById(id);
		List<Category> findAllCategory = categoryService.findAllCategory();
		List<Tag> allTag = tagService.getAllTag();
		for(Category cate:articleById.getCategoryList()) {
			if(cate.getCategoryPid()==0) {
				map.put("bigCate", cate);
			}else {
				map.put("smallCate", cate);
			}
		}
		String str = "";
		for(Tag tag:articleById.getTagList()) {
			str += tag.getTagId() + ",";
		}
		map.put("tagStr", str);
		map.put("categoryList", findAllCategory);
		map.put("tagList", allTag);
		map.put("article",articleById);
		return "article/article_edit";
	}
	@RequestMapping("/lianDong")
	@ResponseBody
	public List<Category> liandong(Integer id,ModelMap map) {
		List<Category> list = categoryService.findSmallCategory(id);
		return list;
	}
	/**
	 * 修改文章信息
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public String edit(ModelMap map,HttpServletRequest request) {
		Article article = new Article();
		//文章id
		article.setArticleId(Integer.parseInt(request.getParameter("articleId")));
		//添加文章标题
		article.setArticleTitle(request.getParameter("articleTitle"));
		//添加文章内容
		article.setArticleContent(request.getParameter("articleContent"));
		//添加添加文章的人id
		User user = (User)request.getSession().getAttribute("user");
		article.setArticleUserId(user.getUserId());
		//添加文章摘要
		String articleContent = HtmlUtil.cleanHtmlTag(request.getParameter("articleContent"));
		article.setArticleSummary((articleContent.length()>150?articleContent.substring(0,150):articleContent));
		//添加修改和创建时间
		article.setArticleCreateTime(new Date());
		article.setArticleUpdateTime(new Date());
		//默认的排序
		article.setArticleOrder(1);
		//文章状态(草稿,或发布)
		article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus" )));
		//一级分类ID
		int parentCateId =Integer.parseInt(request.getParameter("articleParentCategoryId"));
		//二级分类ID
		int childCateId=Integer.parseInt(request.getParameter("articleChildCategoryId"));
		//标签
		//添加分类
		List<Category> cateList = new ArrayList<>(2);
		cateList.add(new Category(parentCateId));
		cateList.add(new Category(childCateId));
		article.setCategoryList(cateList);
		String [] tagIds =request.getParameterValues("articleTagIds");
		//添加标签
		if(tagIds!=null) {
			List<Tag> tagList = new ArrayList<>();
			for(String tag:tagIds) {
				tagList.add(new Tag(Integer.parseInt(tag)));
			}
			article.setTagList(tagList);
		}
		articleService.updateArticle(article);
		return "forward:/article";
	}
	@RequestMapping("/uploadImg")
	public String  uploadImg(MultipartHttpServletRequest request) throws IllegalStateException, IOException {
		MultipartFile file = request.getFile("imgFile");
		String newName = UUID.randomUUID().toString() + ".jpg";
		File destFile = new File("D:/imguploads/"+newName);
		String path ="http://localhost:8080/uploads/" + newName;
		file.transferTo(destFile);
		return "{\"error\":0,\"url\":\""+path+"\"}" ;
	}
}
